package com.liliudong.pinkyponk.api.admin.controller.sys;

import com.liliudong.pinkyponk.api.admin.security.UserDetailsImpl;
import com.liliudong.pinkyponk.biz.sys.request.SysUserRequest;
import com.liliudong.pinkyponk.core.util.R;
import com.liliudong.pinkyponk.core.validator.Login;
import com.liliudong.pinkyponk.security.util.JwtHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Auth
 *
 * @author liliudong
 * @date 2022-08-22 13:38
 **/
@RestController
@RequestMapping("/v1/sys/auth")
@RequiredArgsConstructor
public class SysAuthController {

    private final AuthenticationManager authenticationManager;
    private final JwtHelper jwtHelper;

    /**
     * login
     *
     * @param sysUserRequest
     * @return
     */
    @PostMapping("/login")
    public ResponseEntity<?> login(
            @RequestBody @Validated(Login.class) SysUserRequest sysUserRequest) {
        UsernamePasswordAuthenticationToken authenticate = new UsernamePasswordAuthenticationToken(
                sysUserRequest.getUsername(), sysUserRequest.getPassword());
        Authentication authentication = authenticationManager.authenticate(authenticate);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        String token = jwtHelper.generateToken(userDetails.getSysUser().getUsername());
        return R.of()
                .put("token", token)
                .put("expire", jwtHelper.getExpireTimestamp())
                .get();
    }
}
